/*
 * HWTIMERC1.c
 *
 *  Created on: 27/02/2013
 *      Author: RIchard
 */

#include "HWTIMERC1.h"
#include "../../sensor.h"
#include "../DIO/DIOC1.h"

#define CPU_FREQ     ( 12000000 )                  /* Hz */
#define DIVIDER      ( 8 )
#define HWTIMER_1MS  ( CPU_FREQ / DIVIDER / ( 1000 / HWTIM_nTimerInterval ) ) /* Ms */
#define PWMFREQ      ( CPU_FREQ / DIVIDER / HWTIM_nPWMFreq )

static volatile MSP430_tstTimerARegisters *HWTIM_stTimerA0 = &MSP430_TIMERA0;
static volatile MSP430_tstTimerARegisters *HWTIM_stTimerA1 = &MSP430_TIMERA1;
static volatile uint16 u16TimerCounter;

void HWTIM_vReset( void )
{
   /* SMCLK */
   HWTIM_stTimerA0->TACTL.u2TASSEL = HWTIM_nenSMCLK;
   HWTIM_stTimerA1->TACTL.u2TASSEL = HWTIM_nenSMCLK;

   /* Divider = 8 */
   HWTIM_stTimerA0->TACTL.u2ID = 3;
   HWTIM_stTimerA1->TACTL.u2ID = 3;

   /* Out Mode for PWM */
   HWTIM_stTimerA1->TACCTL[1].u3OUTMOD = HWTIM_nenToggleReset;

   u16TimerCounter = 0;

   HWTIM_vStartPWM();
}

void HWTIM_vStartPWM( void )
{
   /* Period */
   HWTIM_stTimerA1->TACCR[0] = PWMFREQ;

   /* Duty */
   HWTIM_stTimerA1->TACCR[1] = ( PWMFREQ / 2u );

   /* Start Timer */
   HWTIM_stTimerA1->TACTL.u2MC = HWTIM_nenUp;
   HWTIM_stTimerA1->TACTL.biTACLR = True;
}

void HWTIM_vStartTimer( void )
{
   /* Clear counter value */
   HWTIM_stTimerA0->TAR = 0;

   /* Set counter value to count up to */
   HWTIM_stTimerA0->TACCR[0] = HWTIMER_1MS;

   /* Enable interrupt */
   HWTIM_stTimerA0->TACCTL[0].biCCIE = True;

   /* Set timer mode */
   HWTIM_stTimerA0->TACTL.u2MC = HWTIM_nenContinuous;
}

void HWTIM_vStopTimer( void )
{
   HWTIM_stTimerA0->TACCTL[0].biCCIE = False;
   HWTIM_stTimerA0->TACCR[0] = 0;
   HWTIM_stTimerA0->TACTL.u2MC = HWTIM_nenStop;
}

bool HWTIM_boIsTimerRunning( void )
{
   bool boRetVal;

   boRetVal = False;

   if( HWTIM_stTimerA0->TACTL.u2MC != HWTIM_nenStop )
   {
      boRetVal = True;
   }

   return boRetVal;
}

uint16 HWTIM_u16GetCurrentTimerValue( void )
{
   return HWTIM_stTimerA0->TACCR[0];
}

uint16 HWTIM_u16GetCounterValue( void )
{
   return u16TimerCounter;
}

void HWTIM_vClearCounterValue( void )
{
   u16TimerCounter = 0;
}

// Timer A0 interrupt service routine
#pragma vector=TIMER0_A0_VECTOR
__interrupt void HWTIM_vTimer0ISR( void )
{
   /* TEST */
   MSP430_FAST_TOGGLE_PIN_TEST2;

   HWTIM_stTimerA0->TACCR[0] += HWTIMER_1MS;

   APP_unRequests.F.biTimerEvent = 1;
   u16TimerCounter++;

   _BIC_SR_IRQ(LPM3_bits);
}

#pragma vector=TIMER1_A1_VECTOR
__interrupt void HWTIM_vTimer1ISR( void )
{

}
